<?php

// App::uses('ChartManager', 'Lib/chart');
App::uses('StringUtil', 'Lib');
App::uses('RestController', 'Controller');

class ChartController extends RestController {
    var $name = null; // 'Chart'; // riferimento alla cartella delle view
    //var $modelClass = 'Multa';

    // var $components = array('Permission','Acl'); 
    
    public function beforeFilter(){
		// if(!$this->request->is('ajax'))
		parent::beforeFilter();
        $this->Auth->allow('index');
    }
	

    public function index($chartType, $model) {
		try {
			$this->layout="ajax";
			$this->autorender = false;
			$data = $this->{$chartType."_".$model}();
			echo json_encode($data);
			die();
		} catch (Exception $e) {
			CakeLog::error($e->getMessage());
			$this->layout="ajax";
			$this->autorender = false;
			$ret = array('success'=> false,'message'=>$e->getMessage(),'level'=>'error');
			echo json_encode($ret);
            die();
		}
    }

    private function pie_jobber_mestiere() {
		$this->loadModel("Jobber");
		$query = "SELECT MestiereLang.name, count(Jobber.mestiere_id)";
		$query .= " FROM jobber AS Jobber INNER JOIN user AS User ON (Jobber.user_id = User.id)";
		$query .= " LEFT JOIN categories AS Mestiere ON (Jobber.mestiere_id = Mestiere.id)";
		$query .= " left join categories_lang MestiereLang on (Mestiere.id=MestiereLang.reference_id and MestiereLang.locale=". StringUtil::stringToSql(Configure::read("Config.language")) . ")";
		$query .= " WHERE Jobber.stato = 'A' AND User.stato = 'A'";
		$query .= " GROUP BY Jobber.mestiere_id";
		$result = $this->Jobber->query($query);
		return $this->resultToPieData(Hash::flatten($result), 2);
    }

    private function pie_jobber_regione() {
		$this->loadModel("Jobber");
		$query = "SELECT Jobber.region, count(Jobber.region)";
		$query .= " FROM jobber AS Jobber INNER JOIN user AS User ON (Jobber.user_id = User.id)";
		$query .= " WHERE Jobber.stato = 'A' AND User.stato = 'A'";
		$query .= " GROUP BY Jobber.region";
		$result = $this->Jobber->query($query);
		return $this->resultToPieData(Hash::flatten($result), 2);
    }

    public function pie_team_match($localteamId,$visitorteamId) {
    	
		$xmlh2h=simplexml_load_file("http://www.goalserve.com/getfeed/18945090b13942a5834efeec7eb903e2/h2h/".$localteamId."/".$visitorteamId);
		$xmlh2h->overall->total->total[0]->attributes()->games;

		return $this->resultToPieData(Hash::flatten($result), 2);
    }
	
	private function resultToPieData($result, $columns) {
		$flatten_result=Hash::flatten($result);
		$data=array();
		$comodo=array();
		$column=1;
		foreach (array_values($flatten_result) as $key => $value) {
			if ($column % $columns == 0) {
				array_push($comodo, doubleval($value));
				array_push($data,$comodo);
				$comodo=array();
			} else {
				array_push($comodo, $value);
			}
			$column++;
		}
		return $data;
	}

}
?>